package com.hyfrogx.modules.manage.util;

import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.hyfrogx.config.ScoreCoinConfig;
import com.hyfrogx.modules.manage.entity.coin.CoinDetailEntity;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import java.io.IOException;
import java.rmi.ServerException;
import java.util.HashMap;
import java.util.Map;

public class ScoreCoinUtils {

    /**
     * 积分系统手机号加密
     *
     * @param phone
     * @return encrypt
     */
    public static String getRsaPhone(String phone) {
        // 公钥加密
        RSA rsa1 = new RSA(null, ScoreCoinConfig.getPublicKey());
        String encrypt = rsa1.encryptBase64(phone, KeyType.PublicKey);
        return encrypt;
    }

    /**
     * 调用积分系统项目登录接口,获取token
     *
     * @param phone
     * @return
     */
    public static String getToken(String phone) throws IOException {
        // 手机号机密
        String rsaPhone = ScoreCoinUtils.getRsaPhone(phone);
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        HttpPost post = new HttpPost(ScoreCoinConfig.getToken_coin());
        // 请求的body信息
        Map<String, String> map = new HashMap<String, String>();
        map.put("mobile", rsaPhone);
        map.put("code", ScoreCoinConfig.getCode());
        String data = JSON.toJSONString(map);
        // 添加body
        ByteArrayEntity entity = null;
        try {
            entity = new ByteArrayEntity(data.toString().getBytes("UTF-8"));
            entity.setContentType("application/json");
            post.setEntity(entity);
            CloseableHttpResponse response = httpclient.execute(post);
            try {
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity httpEntity = response.getEntity();
                    if (null != httpEntity) {
                        String retSrc = EntityUtils.toString(httpEntity);
                        JSONObject json = new JSONObject(retSrc);
                        if (json.getInt("code") == 0) {
                            return json.getJSONObject("data").getStr("token");
                        } else {
                            return json.getStr("msg");
                        }
                    }
                }
            } finally {
                response.close();
            }
        } catch (ServerException e) {
            return e.getMessage();
        }
        httpclient.close();
        return null;
    }

    /**
     * 发送包体
     * @param coin
     * @param token
     * @return
     * @throws ServerException
     */
    public static Integer sendPackage(CoinDetailEntity coin, String token) throws ServerException {
        // 1.加密object
        String str = JSON.toJSONString(coin);
        RSA rsa1 = new RSA(null, ScoreCoinConfig.getPublicKey());
        String requestForm = rsa1.encryptBase64(str, KeyType.PublicKey);
        Map<String, String> map = new HashMap();
        map.put("encrypt", requestForm);
        // 2.创建httpClient实例.httppost
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost post = new HttpPost(ScoreCoinConfig.getSend_coin1());
        //HttpPost post = new HttpPost("http://localhost:8888/hycoin/app/user/coin");
        //HttpPost post = new HttpPost("http://118.89.246.194:8888/hycoin/app/user/coin");
        //HttpPost post = new HttpPost("http://127.0.0.1:8888/hycoin/app/user/coin");
        // 请求的body信息
        String data = JSON.toJSONString(map);
        ByteArrayEntity entity = null;
        try {
            entity = new ByteArrayEntity(data.toString().getBytes("UTF-8"));
            // 4.请求头
            entity.setContentType("application/json");
            post.setEntity(entity);
            post.setHeader("token", token);
            CloseableHttpResponse response = httpclient.execute(post);
            try {
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity httpEntity = response.getEntity();
                    if (null != httpEntity) {
                        String retSrc = EntityUtils.toString(httpEntity);
                        JSONObject json = new JSONObject(retSrc);
                        return json.getInt("code");
                    }
                }
            } finally {
                response.close();
            }
        } catch (Exception e) {
            throw new ServerException("请求异常");
        }
        return null;
    }

    /**
     * 获取用户总积分
     * @param token
     * @return
     * @throws IOException
     */
    public static Integer getUserCoin(String token) throws IOException {
        // 2.创建httpClient实例.httppost
        CloseableHttpClient httpclient = HttpClients.createDefault();
//		HttpPost post = new HttpPost("http://118.89.248.233:8888/hycoin/app/user/coinCount");
        HttpPost post = new HttpPost(ScoreCoinConfig.getCoin_count());
//		HttpPost post = new HttpPost("http://127.0.0.1:8888/hycoin/app/user/coin");
        try {
            post.setHeader("token", token);
            CloseableHttpResponse response = httpclient.execute(post);
            try {
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity httpEntity = response.getEntity();
                    if (null != httpEntity) {
                        String retSrc = EntityUtils.toString(httpEntity);
                        JSONObject json = new JSONObject(retSrc);
                        return json.getInt("coin");
                    }
                }
            } finally {
                response.close();
            }
        } catch (Exception e) {
            throw new ServerException("请求异常");
        }
        httpclient.close();
        return null;
    }


}
